import axios from 'axios'
import store from '@/store/index'
import router from '@/router'
import { removeToken } from '@/utils/auth'
const baseURL = process.env.VUE_APP_BASE_API
const instance = axios.create({
  baseURL: baseURL

})
// 响应
instance.interceptors.response.use(res => {
  return res.data
}, (err) => {
  console.dir(err)
  if (err.response.status === 401 && err.response.data.code === 10002) {
    store.commit('user/SET_TOKEN', '')
    store.commit('user/UserInfo', null)
    removeToken()
    router.push('/login')
  }
  return Promise.reject(err)
})
// 添加请求头拦截器
instance.interceptors.request.use(config => {
  const token = store.getters.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
}, (err) => {
  console.dir(err)

  return Promise.reject(err)
})
// 无论发送何种请求都data传参数
// method的值不区分大小写
// method可以省略，默认采用get请求

export default (options) => {
  let key = null
  if (options.method) {
    key = options.method.toUpperCase() === 'GET' ? 'params' : 'data'
  } else {
    key = 'params'
  }
  return instance({
    url: options.url,
    method: options.method || 'GET',
    [key]: options.data
  })
}
